import 'package:dio/dio.dart';
import 'package:flutter_simple_watch/interceptor/common_header_interceptor.dart';
import 'package:flutter_simple_watch/interceptor/common_log_interceptor.dart';

import 'interceptor/we_chat_dynamic_url_interceptor.dart';
import 'interceptor/we_chat_param_interceptor.dart';

///@author aidenquan
/// Created by junlintianxia on 1/15/21.

class WeChatApiService {
  static const String WECHAT_BASE_URL = "https://apis.tianapi.com";
  static const String WECHAT_APP_KEY = "01e8ff6168d1053e30439127e587ebd0";

  Dio? _dio;

  ///单例对象
  static WeChatApiService? _instance;

  static WeChatApiService get instance => _getInstance();

  ///构造函数
  WeChatApiService._internal() {
    print("_internal");
  }

  ///获取单例对象
  static WeChatApiService _getInstance() {
    _instance ??= new WeChatApiService._internal();
    return _instance!;
  }

  ///通过 new WeChatApiService() 调用。
  factory WeChatApiService() => _getInstance();

  ///创建dio网络请求对象
  Dio _createDio() {
    final options = BaseOptions(
      baseUrl: WECHAT_BASE_URL,
      connectTimeout: const Duration(milliseconds: 30 * 1000),
      receiveTimeout: const Duration(milliseconds: 30 * 1000),
    );
    final dio = Dio(options);
    // 添加通用拦截器
    for (Interceptor interceptor in getInterceptors()) {
      dio.interceptors.add(interceptor);
    }
    return dio;
  }

  /// 子类可以复写该方法 自定义添加拦截器
  List<Interceptor> getInterceptors() {
    List<Interceptor> interceptors = [];
    interceptors.add(WeChatDynamicUrlInterceptor());
    interceptors.add(CommonHeaderInterceptor());
    interceptors.add(WeChatParamInterceptor());
    interceptors.add(CommonLogInterceptor());
    return interceptors;
  }

  Dio getDio() {
    _dio ??= _createDio();
    return _dio!;
  }
}
